package com.alogic.nginx.xscript;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * nginx配置段落
 * 
 * @author yyduan
 * @since 1.6.12.25 [20190311 duanyy] <br>
 */
public class NginxSection extends Segment {
	/**
	 * 上下文id
	 */
	protected String pid = "$nginx-conf";

	protected String $name;
	
	/**
	 * 间隔
	 */
	protected String $indent = "$nginx-indent";
	
	public NginxSection(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p){
		super.configure(p);
		pid = PropertiesConstants.getString(p, "pid", pid,true);
		$name = PropertiesConstants.getRaw(p,"n","");
		$indent = PropertiesConstants.getString(p, "indent", $indent,true);
	}
	
	@Override
	protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
		StringBuffer content = ctx.getObject(pid);
		if (content == null){
			throw new BaseException("core.e1001","It must be in a ngx-conf context,check your script.");
		}

		String name = PropertiesConstants.transform(ctx, $name, "");
		int indent = PropertiesConstants.getInt(ctx, $indent, 0);
		
		String tabs = getIndent(indent);
		
		content.append("\n").append(tabs).append(name).append(" {");
		
		try{
			ctx.SetValue($indent, String.valueOf(indent + 1));
			super.onExecute(root, current, ctx, watcher);
		}finally{
			ctx.SetValue($indent, String.valueOf(indent));
			content.append("\n").append(tabs).append("}");
		}
	}

	protected static String getIndent(int indent){
		return indent > 0 ? String.format(String.format("%%%ds", indent), "\t") : "";
	}

}
